import React from 'react';
import PropTypes from 'prop-types';
import css from './index.less';
import { observer } from 'mobx-react';
import { computed } from 'mobx';
import Utils from 'common/utils';


const { addEvent, removeEvent } = Utils;

/**
 * 未完成
 */
@observer
export default class Cover extends React.Component {


  static propTypes = {
    mod: PropTypes.object.isRequired,
    active: PropTypes.bool,
  };

  static defaultProps = {
    active: false
  };

  constructor(props) {
    super(props);
    this.state = {
      originX: props.mod.left,
      originY: props.mod.top,
      startX: 0,
      startY: 0,
    };
  }

  componentDidMount() {
    this.onMouseMove = this.onMouseMove.bind(this);
    this.onMouseUp = this.onMouseUp.bind(this);
  }
  componentDidUpdate() {

  }

  componentWillUnmount() {
    this.detachEvent();
  }

  detachEvent() {
    removeEvent(document, 'mousemove', this.onMouseMove);
    removeEvent(document, 'mouseup', this.onMouseUp);
    removeEvent(document, 'mouseleave', this.onMouseUp);
  }

  onMouseUp = (e) => {
    e.stopPropagation();
    e.preventDefault();
    this.detachEvent();
  };

  onMouseMove = (e) => {
    const { mod, simulator: { scale, left, top } } = this.props;
    const { startX, startY, originX, originY } = this.state;
    e.stopPropagation();
    const { pageX, pageY } = e;
    const difX = pageX - startX;
    const difY = pageY - startY;
    mod.update({
      left: originX - left + difX / scale,
      top: originY - top + difY / scale
    });
  };

  @computed get style() {
    const { mod, simulator } = this.props;
    const { scale, left, top } = simulator;
    return {
      left: mod.left * scale + left,
      top: mod.top * scale + top,
      width: mod.width * scale,
      height: mod.height * scale,
    };
  }

  render() {
    const props = {
      className: css.cover,
      style: {
        ...this.style,
      },
      onMouseDown: (e) => {
        e.stopPropagation();
        e.preventDefault();
        const { pageX, pageY } = e;
        addEvent(document, 'mousemove', this.onMouseMove);
        addEvent(document, 'mouseup', this.onMouseUp);
        addEvent(document, 'mouseleave', this.onMouseUp);
        this.setState({
          startX: pageX,
          startY: pageY,
          originX: this.style.left,
          originY: this.style.top,
        });
      }
    };
    return (
      <div {...props} />
    );
  }
}
